package com.rtk.flutter_rtk;


import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.gson.Gson;
import com.southgnss.sdk4business.SdkServiceApi;
import com.southgnss.sdk4business.bean.SdkGnssLocation;
import com.southgnss.sdk4business.impl.SouthGnssDeviceListener;

import io.flutter.Log;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;

public class MainActivity extends FlutterActivity implements MethodChannel.MethodCallHandler {

    private double mRodHeight = 0.0;
    private MethodChannel mChannel;

    private boolean isRegisterListener = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 越早运行越好，初始化需要时间
        SdkServiceApi.requestPermissionsAndInit();
//        checkPermissionAvailable();
        SdkServiceApi.setRodHeight(mRodHeight);

    }

    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);

        GeneratedPluginRegistrant.registerWith(flutterEngine);
        mChannel = new MethodChannel(flutterEngine.getDartExecutor(), "com.rtk.flutter_rtk");
        mChannel.setMethodCallHandler(this);

    }

    private boolean checkPermissionAvailable() {
        if (ContextCompat.checkSelfPermission(MainActivity.this,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(MainActivity.this, "请先授权位置信息权限！", Toast.LENGTH_SHORT).show();
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("提示")
                    .setMessage("本应用需要获得定位权限才能正常使用")
                    .setCancelable(false)
                    .setPositiveButton("同意", (dialog, which) -> ActivityCompat.requestPermissions(
                            MainActivity.this,
                            new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                            120))
                    .setNegativeButton("退出", (dialog, which) -> finish()).show();
            return false;
        }
        return true;
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
        switch (call.method) {
            case "connect":
                if (!SdkServiceApi.isConnected()) {
                    SdkServiceApi.startConnectedActivity();
                }
                result.success(true);
                break;
            case "deviceSettings": //仪器设置
                if(MainApplication.getApplication().isSetting() && SdkServiceApi.isConnected()){
                    return;
                }
                if (!SdkServiceApi.isConnected()){
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            while (true){
                                if (SdkServiceApi.isConnected()) {
                                    SdkServiceApi.startDeviceSettingsActivity();
                                    MainApplication.getApplication().setSetting(true);
                                    break;
                                }
                            }
                        }
                    }).start();
                }
                SdkServiceApi.startDeviceSettingsActivity();
                result.success(true);
                break;
            case "settingPremiss":
                checkPermissionAvailable();
                result.success(true);
                break;
            case "getConnection":
                result.success(SdkServiceApi.isConnected());
                break;
            case "registerListener":
                if (!isRegisterListener) {
                    registerListener();
                    isRegisterListener = true;
                }
                result.success(true);
                break;
            case "destroyListener":
                if (isRegisterListener) {
                    destroyListener();
                    isRegisterListener = false;
                }
                result.success(true);
                break;
        }
    }


    private final SouthGnssDeviceListener southGnssDeviceListener = new SouthGnssDeviceListener() {
        @Override
        public void onSouthGnssDeviceLocation(SdkGnssLocation southLocation) {
            //UTC时间
            long utcTime = southLocation.getUtcTime();

            //卫星数
            int lockSatNum = southLocation.getLockSatNum();
            int viewSatNum = southLocation.getViewSatNum();

            //解状态
            // 1 是单点解  2和9是差分解  4是固定解  5是浮点解  7是基站  6是惯导
            int solutionState = southLocation.getSolutionState();
            String mSolutionStateStr = getSolutionState(solutionState);

            //精度因子
            double pdop = southLocation.getPdop();
            double hdop = southLocation.getHdop();
            double vdop = southLocation.getVdop();
            double hrms = southLocation.getHrms();
            double vrms = southLocation.getVrms();


            //engine==1时为PPP高精度解，engine==0或2时为RTK解
            //一般用户不需要关注
            int engine = southLocation.getEngine();

            //惯导状态
            //0 无效 ，否则 有效
            int tcmState = southLocation.getTcmState();

            //使用CORS播发RTCM坐标系统参数计算
            //0 有效，否则：无效
            int rtcmStatus = southLocation.getRtcmStatus();


            //定位数据，经纬度
            double lat = southLocation.getLat();
            double lon = southLocation.getLon();
            double alt = southLocation.getAlt();

            //定位数据，北东高
            double mN = southLocation.getN();
            double mE = southLocation.getE();
            double mH = southLocation.getH();

//            Log.e("Lat:" , CommonFunction.getDegreeDMS(lat)+"");
//            Log.e("Lon:"  , CommonFunction.getDegreeDMS(lon)+"");
//            Log.e("Alt:"  , String.format("%.3f", alt));
//            Log.e("N:"  , String.format("%.3f", mN));
//            Log.e("E:"  , String.format("%.3f", mE));
//            Log.e("H:"  , String.format("%.3f", mH));
//            Log.e("解状态:"  , mSolutionStateStr);
//            Log.e("杆高:"  , mRodHeight+"");
//            Log.e("锁定卫星数:"  , lockSatNum+"");
//            Log.e("可见卫星数:"  , viewSatNum+"");
//            Log.e("Hrms:"  , String.format("%.3f", hrms));
//            Log.e("Vrms:"  , String.format("%.3f", vrms));
//            Log.e("Pdop:"  , String.format("%.3f", pdop));
//            Log.e("Hdop:"  , String.format("%.3f", hdop));
//            Log.e("Vdop:"  , String.format("%.3f", vdop));
//            Log.e("惯导状态:"  , (tcmState == 0 ? "不可用" : "可用"));
//            Log.e("设备连接状态:"  , (SdkServiceApi.isConnected() ? "已连接" : "未连接"));
            if (mChannel != null) {
                Log.e("设备连接状态:", (SdkServiceApi.isConnected() ? "已连接" : "未连接"));
                mChannel.invokeMethod("getLocationForResult", new Gson().toJson(southLocation), new MethodChannel.Result() {
                    @Override
                    public void success(@Nullable Object result) {

                    }

                    @Override
                    public void error(String errorCode, @Nullable String errorMessage, @Nullable Object errorDetails) {

                    }

                    @Override
                    public void notImplemented() {

                    }
                });
            }
        }
    };

    private String getSolutionState(int solutionState) {
        //解状态 1 是单点解  2和9是差分解  4是固定解  5是浮点解  7是基站  6是惯导
        switch (solutionState) {
            case 1:
                return "单点解";
            case 2:
            case 9:
                return "差分解";
            case 4:
                return "固定解";
            case 5:
                return "浮点解";
            case 6:
                return "惯导";
            case 7:
                return "基站";
        }
        return "";
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isRegisterListener) {
            registerListener();
        }
    }

    public void registerListener() {
        if (SdkServiceApi.isConnected()) {
            SdkServiceApi.registerListener(southGnssDeviceListener);
        }

        Log.e("Height", SdkServiceApi.getRodHeight() + "");
        Log.e("UseTcm", SdkServiceApi.isUseTcm() + "");
        Log.e("设备连接状态:", (SdkServiceApi.isConnected() ? "已连接" : "未连接"));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isRegisterListener) {
            destroyListener();
        }
    }

    public void destroyListener() {
        if (isRegisterListener) {
            SdkServiceApi.unRegisterListener(southGnssDeviceListener);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1001) {
            if (resultCode == RESULT_OK) {

            }
        } else if (requestCode == 1003) {
            if (resultCode == RESULT_OK) {
            }
        }
    }

}

